package mythreads;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

class WorkerThread  implements Runnable{

	private String command;
    
    public WorkerThread(String s){
        this.command=s;
    }
 
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+" Start. Command = "+command+" Start. Time = "+new Date());
        processCommand();
        System.out.println(Thread.currentThread().getName()+" End. Command = "+command+" End. Time = "+new Date());
    }
 
    private void processCommand() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
 
    @Override
    public String toString(){
        return this.command;
    }

}

public class ThreadPool {
	 
    public static void main(String[] args) {
    	SimpleThreadPool();
    	//ScheduledThreadPool();
    }
    
    public static void SimpleThreadPool(){
    	 ExecutorService executor = Executors.newFixedThreadPool(5);
         for (int i = 0; i < 10; i++) {
             Runnable worker = new WorkerThread("" + i);
             executor.execute(worker);
           }
         System.out.println("Current Time is "+new Date());
         executor.shutdown();
         while (!executor.isTerminated()) {
         }
         System.out.println("Finished all threads");
    }
    
    public static void ScheduledThreadPool(){
    	ExecutorService executor = Executors.newScheduledThreadPool(5);;
        for (int i = 0; i < 10; i++) {
            Runnable worker = new WorkerThread("" + i);
            ((ScheduledExecutorService) executor).schedule(worker, 10, TimeUnit.SECONDS);
          }
        System.out.println("Current Time is "+new Date());
        executor.shutdown();
        while (!executor.isTerminated()) {
        }
        System.out.println("Finished all threads");
    }
 
}
